import { 
  createCarousel, 
  updateCarousel, 
  deleteCarousel, 
  getCarouselDetail, 
  pageCarousels, 
  listEnabledCarousels, 
  setCarouselStatus 
} from '@/api/carousel'

const state = {
  carouselList: [],
  enabledCarousels: [],
  total: 0,
  currentCarousel: {}
}

const mutations = {
  SET_CAROUSEL_LIST: (state, { list, total }) => {
    state.carouselList = list
    state.total = total
  },
  SET_ENABLED_CAROUSELS: (state, list) => {
    state.enabledCarousels = list
  },
  SET_CURRENT_CAROUSEL: (state, carousel) => {
    state.currentCarousel = carousel
  }
}

const actions = {
  // 分页获取轮播图列表
  getCarouselList({ commit }, params) {
    return new Promise((resolve, reject) => {
      pageCarousels(params).then(response => {
        const { data } = response
        commit('SET_CAROUSEL_LIST', {
          list: data.records,
          total: data.total
        })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取启用的轮播图
  getEnabledCarousels({ commit }) {
    return new Promise((resolve, reject) => {
      listEnabledCarousels().then(response => {
        const { data } = response
        commit('SET_ENABLED_CAROUSELS', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取轮播图详情
  getCarousel({ commit }, id) {
    return new Promise((resolve, reject) => {
      getCarouselDetail(id).then(response => {
        const { data } = response
        commit('SET_CURRENT_CAROUSEL', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 创建轮播图
  createCarousel({ dispatch }, carouselData) {
    return new Promise((resolve, reject) => {
      createCarousel(carouselData).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 更新轮播图
  updateCarousel({ dispatch }, carouselData) {
    return new Promise((resolve, reject) => {
      updateCarousel(carouselData).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 删除轮播图
  deleteCarousel({ dispatch }, id) {
    return new Promise((resolve, reject) => {
      deleteCarousel(id).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 设置轮播图状态
  setCarouselStatus({ dispatch }, { id, status }) {
    return new Promise((resolve, reject) => {
      setCarouselStatus(id, status).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 